package com.ocom.webapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ocom.common.constant.MapKey;
import com.ocom.common.entity.access.EntityMjGroupPer;
import com.ocom.common.entity.access.EntityMjZoneDate;
import com.ocom.common.entity.aiot.EntityMjDeviceInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.simple.AllPersonRequest;
import com.ocom.common.request.web.*;
import com.ocom.common.request.wx.UserAccessPageSetAccessRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.response.web.GetAccessByUserResponse;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.*;
import com.ocom.common.vo.human.UserListVo;
import com.ocom.common.vo.webapi.PageVO;
import com.ocom.common.vo.webapi.UpdateAccessVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.*;
import com.ocom.webapi.service.AccessService;
import com.ocom.webapi.vo.access.AccessDeviceResetVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hutool.poi.excel.cell.CellUtil.getCellValue;


@Service
public class AccessServiceImpl implements AccessService {
    private final Logger log = LoggerFactory.getLogger(AccessServiceImpl.class);

    @Autowired
    private AccessClientService accessClientService;

    @Autowired
    private SrvpAmhClientService srvpAmhClientService;

    @Autowired
    private HumanClientService humanClientService;

    @Autowired
    private MqSimpleService mqSimpleService;


    @Autowired
    private AiotClientService aiotClientService;


    @Resource
    private RedisUtil redisUtil;
    /**
     * 区域新增
     * */
    @Override
    public Result AreaPageAdd(AddAreaVo addAreaVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),addAreaVo.getComId());
        map.put(mapKey.getKey_areaId(),addAreaVo.getAreaId());
        map.put(mapKey.getKey_regionId(),addAreaVo.getRegionId());
        map.put(mapKey.getKey_areaName(),addAreaVo.getAreaName());
        map.put("indoorState",addAreaVo.getIndoorState());
        map.put("outdoorState",addAreaVo.getOutdoorState());
        return accessClientService.NewArea(map);
    }


    /**
     * 区域修改
     * */
    @Override
    public Result AreaPageModify(ModifyAreaVo modifyAreaVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),modifyAreaVo.getComId());
        map.put(mapKey.getKey_areaId(),modifyAreaVo.getAreaId());
        map.put(mapKey.getKey_regionId(),modifyAreaVo.getRegionId());
        map.put(mapKey.getKey_areaName(),modifyAreaVo.getAreaName());
        map.put(mapKey.getKey_userName(),modifyAreaVo.getUserName());
        map.put("indoorState",modifyAreaVo.getIndoorState());
        map.put("outdoorState",modifyAreaVo.getOutdoorState());

        return accessClientService.UpdateAreaName(map);
    }
    /**
     * 区域删除
     * */
    @Override
    public Result AreaPageDelete(DelAreaVo delAreaVo) {

        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),delAreaVo.getComId());
        map.put(mapKey.getKey_areaId(),delAreaVo.getAreaId());
        return accessClientService.RemoveArea(map);
    }

    /**
     * 区域管理列表（AreaPage/onShow）
     * */
    @Override
    public Result AreaPageOnShow(AreaVo areaVo) {
        return accessClientService.GetAreaList(areaVo);
    }

    /**
     * 门禁设备列表（/AccessDevice/onShow）
     * */
    @Override
    public Result AccessDeviceOnShow(DeviceOnShowVo deviceOnShowVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),deviceOnShowVo.getComId());
        map.put(mapKey.getKey_deviceNo(),deviceOnShowVo.getDeviceNo());
        map.put(mapKey.getKey_deviceName(),deviceOnShowVo.getDeviceName());
        map.put(mapKey.getKey_deviceType(),deviceOnShowVo.getDeviceType());
        map.put(mapKey.getKey_deviceVerType(),deviceOnShowVo.getDeviceVerType());
        map.put(mapKey.getKey_page(),deviceOnShowVo.getPage());
        map.put(mapKey.getKey_size(),deviceOnShowVo.getSize());

        return accessClientService.SearchMachList(map);
    }

    /**
     * 门禁设备新增（/AccessDevice/add）
     * */
    @Override
    public Result AccessDeviceAdd(AccessDeviceVo accessDeviceVo){
//        MapKey mapKey = new MapKey();
        Map<String, Object> map1 = new HashMap<>();
//        map1.put(mapKey.getKey_saasNo(),2);
//        map1.put(mapKey.getKey_agentId(), 0);
//        map1.put(mapKey.getKey_comId(),accessDeviceVo.getComId());
//        map1.put(mapKey.getKey_deviceNo(),accessDeviceVo.getDeviceNo());
//        map1.put(mapKey.getKey_status(),2);

        map1.put("saasNo",2);
        map1.put("agentId",0);
        map1.put("comId",accessDeviceVo.getComId());
        map1.put("deviceNo",accessDeviceVo.getDeviceNo());
        map1.put("status",2);
        Result result = aiotClientService.SetMjDeviceStatusBySaas(map1);
        if (result.getCode()!=200){
            return ResultUtil.error(result.getCode());
        }
//        Result result = srvpAmhClientService.SetDeviceActBySaas(map1);
//        if (result.getCode()!=200){
//            return ResultUtil.error(result.getCode());
//        }
        EntityMjDeviceInfo entityMjDeviceInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityMjDeviceInfo.class);
        Map<String, Object> map = new HashMap<>();
        map.put("comId",accessDeviceVo.getComId());
        map.put("deviceName",accessDeviceVo.getDeviceName());
        map.put("deviceType",entityMjDeviceInfo.getDeviceType());
        map.put("deviceVerType",accessDeviceVo.getDeviceVerType());
        map.put("deviceNo",accessDeviceVo.getDeviceNo());
        map.put("deviceMode",accessDeviceVo.getDeviceMode());
        if(entityMjDeviceInfo.getEndTime() != null ){
            map.put("endTime", DateUtils.dateToStr(entityMjDeviceInfo.getEndTime()));
        }else{
            map.put("endTime", "2052-08-16 16:23:06");
        }
        map.put("status",2);
        map.put("pId", SecurityUtils.getYoCiUser().getId());
        return accessClientService.BindMach(map);
    }


    /**
     * 门禁设备修改（AccessDevice/modify）
     * */
    @Override
    public Result AccessDeviceModify(AccessDeviceVo accessDeviceVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),accessDeviceVo.getComId());
        map.put(mapKey.getKey_deviceName(),accessDeviceVo.getDeviceName());
        map.put(mapKey.getKey_deviceType(),accessDeviceVo.getDeviceType());
        map.put(mapKey.getKey_deviceVerType(),accessDeviceVo.getDeviceVerType());
        map.put(mapKey.getKey_deviceNo(),accessDeviceVo.getDeviceNo());
        map.put(mapKey.getKey_deviceMode(),accessDeviceVo.getDeviceMode());

        map.put(mapKey.getKey_ifAlarm(),accessDeviceVo.getIfAlarm());
        map.put(mapKey.getKey_alarmTimes(),accessDeviceVo.getAlarmTimes());

        map.put("faceAuthCode",accessDeviceVo.getFaceAuthCode());
        map.put("openType",accessDeviceVo.getOpenType());

        String key = "getMachineInfoById:" + accessDeviceVo.getComId() + ":" + accessDeviceVo.getDeviceNo();
        redisUtil.del(key);


        return accessClientService.UpdateMach(map);
    }
    /**
     * 门禁设备区域设置（AccessDevice/setArea））
     * */
    @Override
    public Result AccessDeviceSetArea(SetAreaVo setAreaVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),setAreaVo.getComId());
        map.put(mapKey.getKey_areaId(),setAreaVo.getAreaId());
        map.put(mapKey.getKey_deviceNo(),setAreaVo.getDeviceNo());
        return accessClientService.ChangeMachPlace(map);
    }

    /**
     * 门禁设备删除（AccessDevice/delete）
     * */
    @Override
    public Result AccessDeviceDelete(AccessDeviceVo accessDeviceVo) {

        Map<String, Object> map = new HashMap<>();
        List<Object> list = new ArrayList<>();
        String[] deviceNos = accessDeviceVo.getDeviceNo().split(",");
        for (String deviceNo: deviceNos) {
//            map.put(mapKey.getKey_saasNo(),2);
//            map.put(mapKey.getKey_agentId(), 0);
//            map.put(mapKey.getKey_comId(),accessDeviceVo.getComId());
//            map.put(mapKey.getKey_deviceNo(),deviceNo);
//            Result result = srvpAmhClientService.SetDeviceUnActBySaas(map);
//            if (result.getCode()!=200){
//                log.error("禁用失败："+result);
//            }

            Map<String,String>  objectMap =new HashMap<>();
            objectMap.put("deviceNo",deviceNo);

            map.put("saasNo",2);
            map.put("agentId",0);
            map.put("comId",accessDeviceVo.getComId());
            map.put("deviceNo",deviceNo);
            map.put("status",0);
            Result result = aiotClientService.SetMjDeviceStatusBySaas(map);
            if (result.getCode()!=200){
                objectMap.put("msg",result.getMsg());
                list.add(objectMap);
                continue;
            }

            Integer pId = Math.toIntExact(SecurityUtils.getYoCiUser().getId());
            Result result1 = accessClientService.RemoveMach(deviceNo,accessDeviceVo.getComId(),pId);
            if (result1.getCode()!=200){
                return ResultUtil.error(result1.getCode());
            }
            if (result1.getCode()==200){
                objectMap.put("msg","成功");
                list.add(objectMap);
            }

        }
        return ResultUtil.success(list);
    }
    /**
     * 门禁设备列表（AccessDevice/allOnShow）
     * */
    @Override
    public Result AccessDeviceAllOnShow(AllOnShowVo allOnShowVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),allOnShowVo.getComId());
        map.put(mapKey.getKey_deviceName(),allOnShowVo.getDeviceName());
        map.put(mapKey.getKey_deviceType(),allOnShowVo.getDeviceType());
        map.put(mapKey.getKey_deviceNo(),allOnShowVo.getDeviceNo());
        map.put(mapKey.getKey_page(),allOnShowVo.getPage());
        map.put(mapKey.getKey_size(),allOnShowVo.getSize());
        return accessClientService.FindMach(map);
    }

    /*
     * @Description:人员门禁权限列表
     * @Author: lu
     * @Date: 2022/1/12 13:06
     * @param getAccessByUserRequest:
     * @return: com.ocom.common.resp.Result
     **/
    @Override
    public Result getAccessByUser(GetAccessByUserRequest getAccessByUserRequest) {
        Long companyId=Long.parseLong(getAccessByUserRequest.getComId());
        Long pId=Long.parseLong(getAccessByUserRequest.getPId());
        //向服务获取值
        Result result = accessClientService.getAccessByUser(companyId,pId);
        JSONObject jsonObject=JSONObject.parseObject(JSON.toJSONString(result));

        //判断生产者返回的请求是否成功
        if (jsonObject.getInteger("code")==200){
            JSONArray jsonArray=JSON.parseArray(jsonObject.getString("data"));
            if (jsonArray.size()>0){
                JSONArray jsonArrays=new JSONArray();
                for (int i = 0; i < jsonArray.size(); i++) {
                    AccessListVo accessListVo=JSON.parseObject(jsonArray.getString(i),AccessListVo.class);
                    GetAccessByUserResponse getAccessByUserResponse=new GetAccessByUserResponse();
                    getAccessByUserResponse.setAreaName(accessListVo.getDoorArea());
                    getAccessByUserResponse.setAreaId(String.valueOf(accessListVo.getAreaNo()));
                    getAccessByUserResponse.setGroupName(accessListVo.getGroupName());
                    getAccessByUserResponse.setRegionId(String.valueOf(accessListVo.getRegionId()));
                    getAccessByUserResponse.setGroupNo(String.valueOf(accessListVo.getRoleI()));
                    jsonArrays.add(getAccessByUserResponse);
                }
                return ResultUtil.success(jsonArrays);
            }else {
                return ResultUtil.error(ResultEnum.Err_1001);
            }
        }else {
            return ResultUtil.info(jsonObject.getInteger("code"),"生产服务返回的错误");
        }
    }

    /*
     * @Description:人员门禁权限新增
     * @Author: lu 
     * @Date: 2022/1/12 16:06
     * @param getAccessRequest:  
     * @return: com.ocom.common.resp.Result
     **/
    @Override
    public Result setAccessAdd(GetAccessRequest getAccessRequest) {
        UserAccessPageSetAccessRequest userAccessPageSetAccessRequest=new UserAccessPageSetAccessRequest();
        userAccessPageSetAccessRequest.setAreaNo(Long.valueOf(getAccessRequest.getAreaId()));
        userAccessPageSetAccessRequest.setRoleI(Long.valueOf(getAccessRequest.getGroupNo()));
        userAccessPageSetAccessRequest.setCompanyId(getAccessRequest.getComId());
        userAccessPageSetAccessRequest.setUserId(getAccessRequest.getPId());
        userAccessPageSetAccessRequest.setPId(getAccessRequest.getPId());
        userAccessPageSetAccessRequest.setRegionId(Long.valueOf(getAccessRequest.getRegionId()));
        JSONObject jsonObject=JSONObject.parseObject(JSON.toJSONString(accessClientService.getAccess(userAccessPageSetAccessRequest)));
        if (jsonObject.getInteger("code")==200){
            return ResultUtil.success();
        }else {
            return ResultUtil.info(jsonObject.getInteger("code"),jsonObject.getString("msg"));
        }
    }

    /*
     * @Description:获取时区列表
     * @Author: lu 
     * @Date: 2022/1/13 10:42
     * @param comId:  单位编号
     * @return: com.ocom.common.resp.Result
     **/
    @Override
    public Result getZoneList(Long comId) {
        return accessClientService.getZoneList(comId);
    }

    /*
     * @Description:获取时区设置列表
     * @Author: lu
     * @Date: 2022/1/13 17:14
     * @param getZoneDateListRequest:
     * @return: com.ocom.common.resp.Result
     **/
    @Override
    public Result getZoneDateList(GetZoneDateListRequest getZoneDateListRequest) {
        return accessClientService.getZoneDateList(getZoneDateListRequest);
    }

 /**
     * 导入机器（AccessDevice/importDevice）
     * */
    @Override
    public Result AccessDeviceImportDevice(Long comId,Long deviceType, MultipartFile file)  {
        //        1、用HSSFWorkbook打开或者创建“Excel文件对象”
        //        2、用HSSFWorkbook对象返回或者创建Sheet对象
        //        3、用Sheet对象返回行对象，用行对象得到Cell对象
        //        4、对Cell对象读写。
        //获得文件名
        Workbook workbook = null ;
        String fileName = file.getOriginalFilename();
        if(fileName.endsWith("xls")){
            //2003
            try {
                workbook = new HSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(fileName.endsWith("xlsx")){
            //2007
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                throw new Exception("文件不是Excel文件");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Sheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getLastRowNum();// 指的行数，一共有多少行+
        if(rows==0){
            try {
                throw new Exception("请填写数据");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Integer actSuccessCount =0;
        Integer actErrorCount =0;
        Integer successCount=0;
        Integer errorCount=0;
        List<String> list = new ArrayList<>();
        for (int i = 1; i < rows+1; i++) {
            MapKey mapKey = new MapKey();
            Map<String, Object> map1 = new HashMap<>();
            map1.put(mapKey.getKey_saasNo(),2);
            map1.put(mapKey.getKey_agentId(), 0);
            map1.put(mapKey.getKey_comId(),comId);
            map1.put(mapKey.getKey_status(),2);
            // 读取左端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            if (row != null) {

                // **读取cell**
                //设备编号
                Object deviceNoObj = getCellValue(row.getCell(0));
                String[] deviceNos = JSON.toJSONString(deviceNoObj).split("\"");
                for (String deviceNo:deviceNos) {
                    map1.put(mapKey.getKey_deviceNo(),deviceNo);

                }
                Result result = srvpAmhClientService.SetDeviceActBySaas(map1);
                if (result.getCode()!=200){
                    actErrorCount++;
                }
                if (result.getCode()==200){
                    actSuccessCount++;
                }
                EntityMjDeviceInfo entityMjDeviceInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityMjDeviceInfo.class);
                Map<String, Object> map = new HashMap<>();
                map.put(mapKey.getKey_comId(),entityMjDeviceInfo.getComId());

                map.put(mapKey.getKey_deviceType(),entityMjDeviceInfo.getDeviceType());
                map.put(mapKey.getKey_deviceNo(),entityMjDeviceInfo.getDeviceNo());
                map.put(mapKey.getKey_endTime(),entityMjDeviceInfo.getEndTime());
                map.put(mapKey.getKey_status(),2);
                map.put(mapKey.getKey_pId(), SecurityUtils.getYoCiUser().getId());
                //设备名称
                Object deviceNameObj = getCellValue(row.getCell(1));
                String[] deviceNames = JSON.toJSONString(deviceNameObj).split("\"");
                for (String deviceName: deviceNames) {
                    map.put(mapKey.getKey_deviceName(),deviceName);
                }
                Result result1 = accessClientService.BindMach(map);
                if (result1.getCode() == 200){
                    successCount++;
                }
                if (result1.getCode() != 200){
                    errorCount++;
                    list.add(entityMjDeviceInfo.getDeviceNo());
                }

            }

        }

        Map<String, Object> map = new HashMap<>();
        map.put("actSuccessCount",actSuccessCount);
        map.put("actErrorCount",actErrorCount);
        map.put("successCount",successCount);
        map.put("errorCount",errorCount);
        map.put("deviceNos",list);
        return ResultUtil.success(map);
    }

    /*
     * @Description:设置日期时区新增
     * @Author: lu 
     * @Date: 2022/1/14 14:34
     * @param setDateZoneRequest:  
     * @return: com.ocom.common.resp.Result
     **/
    @Override
    public Result setDateZoneAdd(SetDateZoneRequest setDateZoneRequest) {
        EntityMjZoneDate entityMjZoneDate=new EntityMjZoneDate();
        entityMjZoneDate.setZoneNo(setDateZoneRequest.getZoneNo());
        entityMjZoneDate.setDate(setDateZoneRequest.getDate());
        entityMjZoneDate.setComId(setDateZoneRequest.getComId());
        entityMjZoneDate.setDayDate(setDateZoneRequest.getDayDate());
        return accessClientService.setDateZone(entityMjZoneDate);
    }

    @Override
    public Result removeDateZone(RemoveDateZoneRequest removeDateZoneRequest) {
        EntityMjZoneDate entityMjZoneDate=new EntityMjZoneDate();
        entityMjZoneDate.setDate(removeDateZoneRequest.getDate());
        entityMjZoneDate.setComId(removeDateZoneRequest.getComId());
        return accessClientService.removeDateZone(entityMjZoneDate);
    }

    /*
     * @Description:2.5.3.4.区域权限组列表（AccessControlPerson/groupList）
     * @Author: lu
     * @Date: 2022/1/18 15:18
     * @param map:
     * @return: com.ocom.common.resp.Result
     **/
    @Override
    public Result getGroupListByArea(Map<String, String> map) {
        Long companyId=Long.parseLong(map.get("comId"));
        Long areaNo=Long.parseLong(map.get("areaId"));
        Result r=accessClientService.getGroupListByArea(companyId,areaNo);
        if (r.getCode()==200){
            JSONArray jsonArray=JSON.parseArray(JSON.toJSONString(r.getData()));
            List<Map<String,String>> list=new ArrayList<>();
            for (Object groupList : jsonArray) {
                Map<String,Object> jsonMap=JSON.parseObject(JSON.toJSONString(groupList),Map.class);
                Map<String,String> retMap=new HashMap<>();
                retMap.put("groupNo", String.valueOf(jsonMap.get("roleI")));
                retMap.put("groupName", String.valueOf(jsonMap.get("groupName")));
                list.add(retMap);
            }
            return ResultUtil.success(list);
        }else {
            return r;
        }
    }


    /**获取区域信息*/
    @Override
    public Result AccessGetAreaInfo(Long comId,Integer regionId) {
        return accessClientService.GetAreaInfo(comId,regionId,null,"");
    }

    /**
     * 区域权限列表 （AccessControlPerson/getAreaGroupList）
     * */
    @Override
    public Result AccessControlPersonGetAreaGroupList(Long companyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("companyId",companyId);
        return accessClientService.GetAreaGroupList(map);
    }

    /**
     * 重置设备白名单（AccessDevice/reset）
     * */
    @Override
    public Result AccessDeviceReset(AccessDeviceResetVo accessDeviceResetVo) {
        return accessClientService.MachReset(accessDeviceResetVo.getComId(),accessDeviceResetVo.getMachNo());
    }

    @Override
    public Result updateUserAccess(UpdateAccessVo updateAccessVo) {
        if(updateAccessVo.getComId()==null || updateAccessVo.getComId() <= 0 ){
            log.info("参数【{}】，异常【{}】",updateAccessVo,"ComId 空");
            return null;
        }

        UserListVo userListVo=new UserListVo();
        userListVo.setStatus(0);
        userListVo.setPage(1);
        userListVo.setSize(10);
        Result result = null;
        if(updateAccessVo.getType()==1){
            if(CommonUtil.isNull(updateAccessVo.getPCode())){
                log.info("参数【{}】，异常【{}】",updateAccessVo,"pcode 空");
                return null;
            }
            userListVo.setComId(updateAccessVo.getComId());
            userListVo.setPCode(updateAccessVo.getPCode());
            result = humanClientService.GetPersonnelList(userListVo);
        }
        if(updateAccessVo.getType()==2){
            if(CommonUtil.isNull(updateAccessVo.getUserName())){
                log.info("参数【{}】，异常【{}】",updateAccessVo,"UserName 空");
                return null;
            }
            userListVo.setComId(updateAccessVo.getComId());
            userListVo.setPName(updateAccessVo.getUserName());
            result = humanClientService.GetPersonnelList(userListVo);
        }
        if(updateAccessVo.getType()==3){
            if(CommonUtil.isNull(updateAccessVo.getIdentity())){
                log.info("参数【{}】，异常【{}】",updateAccessVo,"UserName 空");
                return null;
            }
            userListVo.setComId(updateAccessVo.getComId());
            userListVo.setPIdentity(updateAccessVo.getIdentity());
            result = humanClientService.GetPersonnelList(userListVo);
        }
        if(updateAccessVo.getType()==4){
            if(CommonUtil.isNull(updateAccessVo.getPhone())){
                return null;
            }
            userListVo.setComId(updateAccessVo.getComId());
            userListVo.setPPhone(updateAccessVo.getPhone());
            result = humanClientService.GetPersonnelList(userListVo);
        }

        List<Long>  pids = new ArrayList<>();

        if(updateAccessVo.getType()==5){
            if(updateAccessVo.getPId()==null || updateAccessVo.getPId()<=0){
                return null;
            }
            pids.add(updateAccessVo.getPId());
        }

        if(result!=null && result.getCode() == 200 ){
            Gson gson =new Gson();
            PageVO result1 = gson.fromJson(gson.toJson(result.getData()),PageVO.class);
            List<Object> list1 = result1.getList();
//            System.out.println(result1);
//            System.out.println(list1);
            if(list1!=null && list1.size()>0) {
                for (Object object : list1) {
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object),JSONObject.class);
                    pids.add(jsonObject.getLong("pId"));
                }
            }
        }

        if(pids.size()>0){
            ChangeAccess(updateAccessVo.getComId(),pids);
        }
        return  null;

    }

    @Override
    public Result importAreaAccess(Long comId, Long areaNo,Integer type, MultipartFile file) {
        Workbook workbook = null ;
        String fileName = file.getOriginalFilename();
        if(fileName.endsWith("xls")){
            //2003
            try {
                workbook = new HSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(fileName.endsWith("xlsx")){
            //2007
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                throw new Exception("文件不是Excel文件");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Sheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getLastRowNum();// 指的行数，一共有多少行+
        if(rows==0){
            try {
                throw new Exception("请填写数据");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Long time = System.currentTimeMillis();

        for (int i = 1; i < rows+1; i++) {

            // 读取左端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            if (row != null) {

                // **读取cell**
                //pId
                Object pIdObj = getCellValue(row.getCell(0));
                Long pId = (Long) pIdObj;

                //权限编号
                Object roleIObj = getCellValue(row.getCell(3));
                Long roleI = (Long) roleIObj;
                
                //增量
                if(type == 1){
                    UserAccessPageSetAccessRequest userAccess=new UserAccessPageSetAccessRequest();
                    userAccess.setCompanyId(comId);
                    userAccess.setPId(pId);
                    userAccess.setUserId(pId);
                    userAccess.setAreaNo(areaNo);
                    userAccess.setRoleI(roleI);
                    userAccess.setRegionId(0l);
                    mqSimpleService.ChangeAccess(userAccess);
                }
                //全量
                if(type == 0){
                    redisUtil.hmSet("AreaAccess:"+comId+":areaNo:"+areaNo+":time:"+time,pId,roleI);
                    redisUtil.expire("AreaAccess:"+comId+":areaNo:"+areaNo+":time:"+time,3600l*3l);
                }
            }

        }
        if(type == 0){
//            System.out.println("发送mq");
            AllPersonRequest request =new AllPersonRequest();
            request.setComId(comId);
            request.setAreaNo(areaNo);
            request.setType(1);
            request.setId(time);
            mqSimpleService.allPerson(request);
        }

        return ResultUtil.success();
    }


    public void ChangeAccess(Long compamnyId,List<Long> pids){
        Gson gson =new Gson();
        for (Long pid : pids){
            if(pid==null || pid<=0){
                continue;
            }
            Result result2 = accessClientService.getWhiteUser(compamnyId,pid);
            if(result2.getCode()==200){
                List<Object> list23 = gson.fromJson(gson.toJson(result2.getData()),List.class);
                if(list23!=null && list23.size()>0) {
                    for (Object object4 : list23) {
                        EntityMjGroupPer entityMjGroupPer = JSON.parseObject(JSON.toJSONString(object4),EntityMjGroupPer.class);
                        //修改权限
                        UserAccessPageSetAccessRequest userAccess=new UserAccessPageSetAccessRequest();
                        userAccess.setCompanyId(compamnyId);
                        userAccess.setPId(entityMjGroupPer.getPId());
                        userAccess.setUserId(entityMjGroupPer.getPId());
                        userAccess.setAreaNo(entityMjGroupPer.getAreaId());
                        userAccess.setRoleI(entityMjGroupPer.getGroupNo());
                        userAccess.setRegionId(0l);
                        mqSimpleService.ChangeAccess(userAccess);
                    }
                }
            }
        }
    }





}
